<template name="userAddress">
  <view class="container">
    <scroll-view class="address-list">
      <view
        v-for="(address, index) in addresses"
        :key="address.id"
        :class="['address-item', { selected: selectedAddress === address.id }]"
        @tap="selectAddress(address)"
      >
        <view class="address-info">
          <text>{{ address.userName }}</text>
          <text>{{ address.userPhone }}</text>
          <text>{{ address.userAddress }}</text>
        </view>
        <view class="address-phone">
          <button class="edit-btn" @tap.stop="editPhone(index)">✏️</button>
        </view>
      </view>
    </scroll-view>
	
	<!-- 添加地址的弹框 -->
	<uni-popup ref="addAddressPopup" type="dialog">
	  <view class="add-address-modal">
		<view class="modal-content">
		  <text class="modal-title">添加新地址</text>
		  <input v-model="newAddress.userName" placeholder="姓名" />
		  <input v-model="newAddress.userPhone" placeholder="电话" />
		  <input v-model="newAddress.userAddress" placeholder="地址" />
		  <button class="confirm-btn" @tap="addAddressInfo">确认</button>
		  <button class="cancel-btn" @tap="hideAddAddressModal">取消</button>
		</view>
	  </view>
	</uni-popup>
	
	<button class="add-address-btn" @tap="showAddAddressModal">添加新地址</button>
  </view>
</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import { getAddressList,addAddress } from '@/api/http/userAddressInfo';
	import { userAddress } from '@/api/types/userAddress';
	import { onShow } from '@dcloudio/uni-app';

	let addresses = ref<userAddress.userAddressType[]>();
	const selectedAddress = ref<number | null>(null);
	const userId = uni.getStorageSync('userId');
	const addAddressPopup = ref<any>(null); // 用于控制弹框的引用
	
	let newAddress = ref<userAddress.addAddressType>({
	  userId: userId, // 从本地存储中获取的 userId
	  userName: '',
	  userPhone: '',
	  userAddress: '',
	});

	// 获取地址列表的方法
	const fetchAddresses = async () => {
	  try {
		let data = await getAddressList(userId);
		addresses.value = data;
	  } catch (error) {
		console.error('获取地址列表失败:', error);
		// 可以在这里添加错误处理逻辑，如显示提示信息
	  }
	};

	// 删除指定地址信息的方法
	const delAddresses = async () => {
	  try {
		let data = await getAddressList(userId);//传入地址主键
		addresses.value = data;
	  } catch (error) {
		console.error('获取地址列表失败:', error);
		// 可以在这里添加错误处理逻辑，如显示提示信息
	  }
	};
	
	// 修改指定地址信息的方法 
	const editAddresses = async () => {
	  try {
		let data = await getAddressList(userId);//传入地址主键
		addresses.value = data;
	  } catch (error) {
		console.error('获取地址列表失败:', error);
		// 可以在这里添加错误处理逻辑，如显示提示信息
	  }
	};
	
	// 在组件挂载后自动调用获取地址列表的方法
	onShow(() => {
	  fetchAddresses();
	});

	// 选择地址的方法
	const selectAddress = (address: userAddress.userAddressType) => {
	  // 发送选中的地址数据
	  uni.$emit('addressSelected', address);
	  // 返回上一个页面
	  uni.navigateBack();
	};
	
	// 编辑电话的方法（假设存在）
	const editPhone = (index: number) => {
	  // 编辑逻辑
	};
	
	// 显示添加地址的弹框
	const showAddAddressModal = () => {
	  addAddressPopup.value.open();
	};
	
	// 隐藏添加地址的弹框
	const hideAddAddressModal = () => {
	  console.log("hideAddAddressModal 被调用"); // 调试信息
	  addAddressPopup.value.close();
	};
	
	// 添加新地址的方法
	const addAddressInfo = async () => {
		
	  if (!newAddress.value.userName || !newAddress.value.userPhone || !newAddress.value.userAddress) {
		uni.showToast({
		  title: '请填写完整地址信息',
		  icon: 'none'
		});
		return;
	  }
	  try {
	    // 构造请求参数
	    const requestData = {
		  userId: userId, // 从本地存储中获取的 userId
		  userPhone: newAddress.value.userPhone,
		  userAddress: newAddress.value.userAddress,
		  userName: newAddress.value.userName,
	    };
	    const response = await addAddress(requestData);
	    if (response == true) {
		  // 添加成功后，刷新地址列表
	      fetchAddresses();
	      // 清空表单
	      newAddress.value = { userName: '', userPhone: '', userAddress: '', userId: userId };
	      // 关闭弹框
	      hideAddAddressModal();
	    } else {
	      console.error('添加地址失败:', response.msg);
	    }
	  } catch (error) {
	    console.error('添加地址失败:', error);
	  }
	};
</script>

<style scoped lang="scss">
	.container {
	  padding: 20px;
	}

	.add-address-btn {
	  margin-bottom: 20px;
	  background-color: #007aff;
	  color: white;
	  padding: 10px;
	  border-radius: 5px;
	  text-align: center;
	}

	.address-list {
	  list-style: none;
	  padding: 0;
	}

	.address-item {
	  display: flex;
	  justify-content: space-between;
	  padding: 10px;
	  margin-bottom: 10px;
	  border: 1px solid #ddd;
	  border-radius: 5px;
	  transition: background-color 0.3s ease;

	  &.selected {
		background-color: #e0f7fa;
	  }
	}

	.address-info {
	  display: flex;
	  flex-direction: column;
	}

	.address-phone {
	  margin-left: auto;
	}

	.edit-btn {
	  background: none;
	  border: none;
	  cursor: pointer;
	}

	.add-address-modal {
	  padding: 20px;
	  background-color: white;
	  border-radius: 10px;
	}

	.modal-content {
	  display: flex;
	  flex-direction: column;
	}

	.modal-title {
	  font-size: 18px;
	  font-weight: bold;
	  margin-bottom: 20px;
	}

	input {
	  margin-bottom: 15px;
	  padding: 10px;
	  border: 1px solid #ddd;
	  border-radius: 5px;
	}

	.confirm-btn {
	  background-color: #007aff;
	  color: white;
	  padding: 10px;
	  border-radius: 5px;
	  text-align: center;
	  margin-bottom: 10px;
	}

	.cancel-btn {
	  background-color: #ff3b30;
	  color: white;
	  padding: 10px;
	  border-radius: 5px;
	  text-align: center;
	}

	.add-address-btn {
	  margin-bottom: 20px;
	  background-color: #007aff;
	  color: white;
	  padding: 10px;
	  border-radius: 5px;
	  text-align: center;
	}
</style>